<template>
  <span class="detail-forms">
    <el-dialog :visible.sync="drawer" width="500px" :title="title" destory-on-close :before-close="beforeClose">
      <div v-if="drawer" class="add-drawer-wrap">
        <div class="drawer-content">
          <div class="form-content">
            <MyForm
              ref="myForm"
              :form-conf="formConf"
              :form-data="formData"
              :rules="rules"
              label-width="93px"
            ></MyForm>
          </div>
        </div>

        <div class="drawer-footer">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="saveClick">保存</el-button>
        </div>
      </div>
    </el-dialog>
  </span>
</template>

<script setup>
import { ref, computed, reactive, nextTick } from 'vue'
import MyForm from '@/components/MyForm/index.vue'
import { addParameter, updateParameter } from '@/api/rule-management'
import { MessageBox, Notification } from 'element-ui'
import _ from 'loadsh'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'
const props = defineProps({
  dataTypeList: {
    type: Array,
    required: true
  }
})
const preData = ref('')
const beforeClose = (done) => {
  if (preData.value === JSON.stringify(formData.value)) {
    done()
  } else {
    MessageBox.confirm('数据未保存，点击确定后数据将不保存，是否确定？', '提示').then(done)
  }
}
const title = ref('')
const emits = defineEmits(['saved'])
const drawer = ref(false)

const initData = JSON.stringify({
  parameterName: '',
  // parameterKey: '',
  dataType: '',
  required: 0,
  description: ''
})
const formData = ref(JSON.parse(initData))
const resetFromData = () => {
  formData.value = JSON.parse(initData)
}
const rules = reactive({
  parameterName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  // parameterKey: [{ required: true, message: '参数英文名称不能为空', trigger: 'blur' }],
  dataType: [{ required: true, message: '数据类型不能为空', trigger: 'change' }],
  required: [{ required: true, message: '是否必填不能为空', trigger: 'change' }]
})
const operationType = ref('')
const nameDisabled = ref(false)
const show = (type, value, row) => {
  drawer.value = true
  operationType.value = type
  nameDisabled.value = false
  if (type === 'add') {
    resetFromData()
    formData.value.parameterModuleId = value
    formData.value.parentParameterId = row.parameterId
    if (row && row.parameterId !== 0) {
      if (row.dataType === 3) {
        title.value = '添加子元素'
        formData.value.parameterName = 'items'
        nameDisabled.value = true
      } else {
        title.value = '添加子对象'
      }
    } else {
      title.value = '新建变量'
    }
  } else if (type === 'edit') {
    formData.value = _.cloneDeep(value)
    title.value = '编辑变量'
    nameDisabled.value = row.nameDisabled
  }
  nextTick(() => {
    preData.value = JSON.stringify(formData.value)
  })
}
const cancelClick = () => {
  if (preData.value === JSON.stringify(formData.value)) {
    drawer.value = false
  } else {
    MessageBox.confirm('数据未保存，点击确定后数据将不保存，是否确定？', '提示').then(() => {
      drawer.value = false
    })
  }
}

let addOrEditParameterRequestId = generateUUID()
const myForm = ref()
const saveClick = () => {
  const saveState = myForm.value.submitForm()
  if (saveState) {
    if (defaultSettings.isWPF || defaultSettings.isCEF) {
      addOrEditParameterRequestId = generateUUID()
      let message = {
        RequestUrl: process.env.VUE_APP_URL + '/parameter/' + (operationType.value === 'add' ? 'add' : 'update'),
        RequestMethod: 'POST',
        Headers: {
          contentType: 'application/json'
        },
        QueryParameter: {},
        RequestBody: formData.value,
        WebInfo: {
          requestId: addOrEditParameterRequestId
        }
      }
      postMessage(message)
    } else {
      let operation = operationType.value === 'add' ? addParameter : updateParameter
      operation(formData.value).then(() => {
        emits('saved')
        Notification({
          type: 'success',
          title: '成功',
          message: operationType.value === 'add' ? '新增完成' : '编辑完成'
        })
        drawer.value = false
      })
    }
  }
}

const dataHandle = (result) => {
  let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
  if (e.data.webInfo.requestId === addOrEditParameterRequestId) {
    let res = e.data.response
    if (res.success) {
      emits('saved')
      Notification({
        type: 'success',
        title: '成功',
        message: operationType.value === 'add' ? '新增完成' : '编辑完成'
      })
      drawer.value = false
    } else {
      Notification({
        type: 'error',
        title: '错误',
        message: res.message
      })
    }
  }
}
receivedMessage(dataHandle)

// 表单配置
const formConf = computed(() => [
  {
    prop: 'parameterName',
    label: '名称',
    type: 'input',
    otherProps: {
      style: { width: '100%' },
      disabled: nameDisabled.value,
      title: title.value === '添加子元素' ? '数组子元素名称默认为items' : '',
      maxlength: '50',
      paddingRight: 45,
      'show-word-limit': true
    }
  },
  // {
  //   prop: 'parameterKey',
  //   label: '参数英文名称',
  //   type: 'input',
  //   otherProps: {
  //     style: { width: '100%' },
  //     maxlength: '20',
  //     paddingRight: 45,
  //     'show-word-limit': true
  //   }
  // },
  {
    prop: 'dataType',
    label: '数据类型',
    type: 'select',
    selectOptions: props.dataTypeList,
    otherProps: {
      disabled: !!formData.value?.children?.length,
      title: formData.value?.children?.length ? '有子对象时，不可编辑数据类型！' : ''
    }
  },
  // {
  //   prop: 'required',
  //   label: '是否必填',
  //   type: 'switch',
  //   otherProps: {
  //     activeValue: 1,
  //     inactiveValue: 0,
  //     activeColor: '#1677FF',
  //     inactiveColor: '#ff4949'
  //   }
  // },
  {
    prop: 'description',
    label: '说明',
    type: 'input',
    otherProps: {
      type: 'textarea',
      style: { width: '100%' },
      maxlength: '255',
      paddingRight: 45,
      'show-word-limit': true
    }
  }
])

defineExpose({ show })
</script>

<style lang="scss" scoped>
.add-drawer-wrap {
  height: 100%;
  display: flex;
  flex-direction: column;
  .drawer-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    .form-content {
      flex: 1;
      max-height: 800px;

      .el-scrollbar ::v-deep .el-scrollbar__wrap {
        overflow-x: hidden;
      }
    }
    .title {
      font-size: 16px;
      font-weight: bold;
      color: #333333;
      padding: 20px 0;
    }
    .label {
      font-size: 14px;
      color: #333333;
      + .value {
        font-weight: bold;
      }
      + .el-input {
        width: 200px;
      }
    }
    > .device-info {
      .device-search {
        .search-item {
          margin-right: 10px;
        }
      }
    }
    > .spot-inspection-plan {
      > .spot-inspection-template {
        padding-bottom: 10px;
        > .template-name {
          margin-right: 10px;
        }
      }
    }
  }
  > .drawer-footer {
    height: 46px;
    display: flex;
    align-items: center;
    padding-left: auto;
    justify-content: flex-end;
    flex-shrink: 0;
  }
}
.preview {
  padding: 0 30px 20px;
  .title {
    font-size: 18px;
    font-weight: 700;
    line-height: 80px;
  }
}
</style>
